<?php 
namespace xfyzf\api\controller;
use xfyzf\api\controller\Pay_Money_Api;
use lib\XFCaptcha;

class Api{
    private $Captcha;
    public function __construct() {
        $this->Captcha = new XFCaptcha(CaptchaCode);
    }
    public function captcha(){
        $this->Captcha->generateCaptcha();
    }
    public function app_cron(){
        // 获取 GET 参数
        $jsonData =input('input')?:input();
        // var_dump();exit;
        // 解码 JSON 数据
        $decodedData = $jsonData;
        
        // 如果解码失败，$decodedData 将为 null
        if ($decodedData === null && json_last_error() !== JSON_ERROR_NONE) {
            $decodedData = ['error' => 'Invalid JSON data'];
        }
        // 构建要写入文件的数据
        $logData = [
            'timestamp' => date('Y-m-d H:i:s'),
            'ip' => http_ip(),
            'data' => $decodedData
        ];
        // 将数据写入文件
        file_put_contents("apidemo.json", json_encode($logData, JSON_PRETTY_PRINT) . ",", FILE_APPEND);
        echo 'success';exit;
    }
    public function query(){
        $postdata = input("post");
        $pid      = $postdata['pid'];
        $qr_id    = $postdata['qr_id'];
        $time     = $postdata['time'];
        $sign     = $postdata['sign'];
        if(empty($pid) || empty($qr_id) || empty($time) || empty($sign))exitjson(-1,'所有参数不可为空！');
        $userrow = $this->userrow($pid);
        if(!$userrow)exitjson(-1,'商户不存在');
        if(!$this->verifysign($postdata,$userrow['key']))exitjson(-1,'签名效验失败！');
        $sql = "SELECT * FROM pay_qrlist WHERE  `pid` = :pid AND `id`= :id LIMIT 1";
        $params = array(
            'pid'=>$pid,
            'id'=>$qr_id
            );
        $result = safeSqlQuery($sql, $params)['result'][0]??'';
        
        if(!$result)exitjson(-1,'二维码ID不存在');
        
        $data = array(
            'qr_id'=>$result['id'],
            'type'=>$result['type'],
            'status'=>$this->status($result['status']),
            'hook_type'=>$this->hook_type($result)
            );
        exitjson(200,"success",$data);
    }
    public function order(){
        $postdata        = input("post");
        $pid             = $postdata['pid'];
        $out_trade_no    = $postdata['out_trade_no'];
        $time            = $postdata['time'];
        $sign            = $postdata['sign'];
        if(empty($pid) || empty($out_trade_no) || empty($time) || empty($sign))exitjson(-1,'所有参数不可为空！');
        $userrow = $this->userrow($pid);
        if(!$userrow)exitjson(-1,'商户不存在');
        if(!$this->verifysign($postdata,$userrow['key']))exitjson(-1,'签名效验失败！');
        $sql = "SELECT * FROM pay_order WHERE  `out_trade_no` = :out_trade_no AND `pid`= :pid LIMIT 1";
        $params = array(
            'out_trade_no'=>$out_trade_no,
            'pid'=>$pid
            );
        $result = safeSqlQuery($sql, $params)['result'][0]??'';
        if(!$result)exitjson(-1,'商户订单号不存在');
        $status = array(
            '1'=>'已支付',
            '2'=>'订单超时',
            '0'=>'未支付'
            );
        $data = array(
            'trade_no'=>$result['trade_no'],
            'out_trade_no'=>$result['out_trade_no'],
            'type'=>$result['type'],
            'name'=>$result['name'],
            'money'=>$result['money'],
            'price'=>$result['price'],
            'qr_id'=>$result['qr_id'],
            'addtime'=>$result['addtime'],
            'endtime'=>$result['endtime'],
            'status'=>$status[$result['status']],
        );
        exitjson(200,'success',$data);
    }
    public function pc_login(){
        $postdata  = input("post");
        $user      = $postdata['user'];
        $pwd       = $postdata['pwd'];
        if(empty($user) || empty($pwd))exitjson(-1,'账号和密码不可为空!');
        $userrow_pid = $this->userrow($user);
        if(!$userrow_pid){
            $userrow_user = $this->userrow_user($user);
            if(!$userrow_user)exitjson(-1,'账号或密码错误');
            $pass = md5(md5($pwd));
            if($userrow_user['pass']!=$pass)exitjson(-1,'账号或者密码错误');
            $token = json_encode(array("pid"=>$userrow_user['pid'],"key"=>$userrow_user['key']));
            $token= aes256auth($token,PCTOKENKEY);
            exitjson(200,'登录成功！',array("token"=>$token));
        }else{
            if($userrow_pid['key'] == $pwd){
                $token = json_encode(array("pid"=>$userrow_pid['pid'],"key"=>$userrow_pid['key']));
                $token= aes256auth($token,PCTOKENKEY);
                exitjson(200,'登录成功！',array("token"=>$token));
            }else{
                exitjson(-1,'pid或key错误');
            }
        }
    }
    public function pc_home(){
        global $conf;
        $token = input("post")['token'];
        if(empty($token))exitjson(-1,'token不可为空！');
       
        $authtoken = $this->pctokenverify($token);
        if(!$authtoken)exitjson(-1,'token信息错误！');
        $pid = $authtoken['pid'];
        $userrow = $this->userrow($pid);
        $data = array(
            'pid'=>$userrow['pid'],
            'key'=>$userrow['key'],
            'money'=>$userrow['money'],
            'qr_nums'=>$userrow['qr_nums'],
            'kfqq'=>$conf['qq'],
            'qq'=>$userrow['qq'],
            'webname'=>$conf['sitename'],
            'status'=>$userrow['zt']
            );
        exitjson(200,'success',$data);
    }
    public function pc_upqrcode(){
        global $date;
        $postdata = input("post");
        $token    = $postdata['token'];
        $cookie   = $postdata['cookie'];
        $type     = $postdata['type'];
        $uid      = $postdata['uid'];
        $qr_url   = $postdata['qr_url'];
        if(empty($token) || empty($cookie) || empty($type) || empty($uid))exitjson(-1,'所有参数不可为空！');
        // if($type  == 'wxpay')exitjson(-1,'不支持微信自动新增二维码');
        $authtoken = $this->pctokenverify($token);
        if(!$authtoken)exitjson(-1,'token信息错误！');
        $pid = $authtoken['pid'];
        $userrow = $this->userrow($pid);
        $Pay_Money = '0.00';
        if($type !='wxpay'){
            $Pay_Money_Api = Pay_Money_Api::Get_pay_money($type, $cookie);
            if($money['money']>=0.01)$Pay_Money = $money['money'];else$Pay_Money = '0.00';
        }
        $qr_url='无';
        $sql = "SELECT * FROM pay_qrlist WHERE pid='{$pid}' and type='{$type}' and uin='{$uid}' and hook_type='1' limit 1";
        $qr_row = executeSQLQuery($sql);
        if($qr_row){
            $sql = "update `pay_qrlist` set `cookie`='{$cookie}',`money`='{$Pay_Money}',`status`='1'  where id='{$qr_row['id']}'";
            executeSQLQuery($sql,'update');
            exitjson(200,'更新成功！');
        }else{
            $sql = "insert into `pay_qrlist` (`pid`,`type`,`qr_url`,`beizhu`,`uin`,`cookie`,`status`,`money`,`hook_type`,`addtime`,`endtime`) values ('{$pid}','{$type}','{$qr_url}','{$uid}','{$uid}','{$cookie}','0','{$Pay_Money}','1','{$date}','{$date}')";
            if(executeSQLQuery($sql,'insert'))exitjson(200,'添加成功');
            exitjson(-1,'添加失败！');
        }
    }
    public function pc_cron(){
        $postdata  = input("post");
        $token     = $postdata['token'];
        $type      = $postdata['type'];
        $uid       = $postdata['uid'];
        $cookie    = $postdata['cookie'];
        if(empty($token) || empty($type) || empty($uid) || empty($cookie))exitjson(-1,'所有参数不可为空');
        $authtoken = $this->pctokenverify($token);
        if(!$authtoken)exitjson(-1,'token信息错误！');
        $pid = $authtoken['pid'];
        $userrow = $this->userrow($pid);
        $sql = "SELECT * FROM pay_qrlist WHERE pid=:pid and type=:type and uin=:uid and hook_type=:hook_type limit 1";
        $paramsSelect = [
            'pid' => $pid,
            'type'=> $type,
            'uid' => $uid,
            'hook_type'=>1
        ];
        $qr_row = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$qr_row)exitjson(-1,'二维码不存在！');
        $Pay_Money = '0.00';
        if($type !='wxpay'){
            $Pay_Money_Api = Pay_Money_Api::Get_pay_money($type, $cookie);
            if($money['money']>=0.01)$Pay_Money = $money['money'];else$Pay_Money = '0.00';
        }
        $timess=time()+  mt_rand(45, 80);
        if($qr_row['crontime']<time() + mt_rand(3, 5) ){
            $sql = "update `pay_qrlist` set `money`='{$Pay_Money}',`cookie`='{$cookie}',`crontime`='{$timess}' WHERE `id`='{$qr_row['id']}'";
            if(executeSQLQuery($sql,'update'))exitjson(200,'更新成功');
            exitjson(-1,'更新失败！');
        }
        exitjson(200,'无需更新');
    }
    public function pc_notify(){
        $postdata  = input("post");
        $token     = $postdata['token'];
        $type      = $postdata['type'];
        $money     = $postdata['money'];
        $uid       = $postdata['uid'];
        $time      = time();
        if(empty($token) || empty($type) || empty($money) || empty($uid))exitjson(-1,'所有参数不可为空');
        $authtoken = $this->pctokenverify($token);
        if(!$authtoken)exitjson(-1,'token信息错误！');
        $pid = $authtoken['pid'];
        $userrow = $this->userrow($pid);
        $sql = "SELECT * FROM pay_qrlist WHERE pid=:pid and type=:type and uin=:uid and hook_type=:hook_type limit 1";
        $paramsSelect = [
            'pid' => $pid,
            'type'=> $type,
            'uid' => $uid,
            'hook_type'=>1
        ];
        $qr_row = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$qr_row)exitjson(-1,'二维码不存在！');
        $sql = "SELECT * FROM pay_order WHERE status=:status  and type=:type and price=:money and outtime>:time and pid = :pid and qr_id = :qr_id  limit 1";
        $paramsSelect = [
            'pid' => $pid,
            'type'=> $type,
            'money' => $money,
            'time'=>$time,
            'qr_id' => $qr_row['id'],
            'status'=>0
        ];
        $srow = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        $typename = array(
            'wxpay'=>'微信PC挂机',
            'qqpay'=>'QQpc挂机',
            'alipay'=>'支付宝PC挂机'
            );
        if($srow){
            if($srow['status'] == '0'){
                $E_type = $typename[$type];
                $url=creat_callback($srow);
                $data=get_curl($url['notify']);
                xfhtemail($pid,$money,$E_type,$srow['name'],$srow['trade_no']); 
                createLog($pid,'自动回调订单('.$E_type.')：'.$srow['trade_no'],http_ip());
                $arr = array(
                    'trade_no'=>$srow['trade_no'],
                    'money'=>$money,
                    'qr_id'=>$qr_row['id']
                );
                exitjson(200,'success',$arr);
            }
        }else{
            exitjson(-1,'无匹配金额');
        }
    }
    
    private function verifysign($post,$key){
        if(!$post)return false;
        $sign = $this->sign($post,$key);
        
        if($sign === $post['sign']){
            return true;
        }else{
            return false;
        }
    }
    
    private function sign($post,$key){
        ksort($post);
        reset($post);
        
        $signstr = '';
        foreach ($post as $k => $v) {
            if ($k != "sign" && $k != "sign_type" && $k != "s" && $k != "act"  && $k != "_input_charset" && $v != '' ) {
                $signstr .= $k . '=' . $v . '&';
            }
        }
        $signstr = substr($signstr, 0, -1);
        $signstr .= $key;
        
        $sign = md5($signstr);
        return $sign;
         
    }
    private function status($status) {
        return ($status == 1) ? '在线' : '掉线';
    }
    private function hook_type($qr_row) {
        $zh = ''; // 初始化返回的描述信息
    
        // 根据支付类型设置挂机方式描述
        $zh .= ($qr_row['type'] == 'alipay') ? ( // 如果是支付宝支付
            ($qr_row['hook_type'] == '0') ? '云端挂机->' : 'PC挂机->' // 根据挂机类型设置挂机方式
        ) : (
            ($qr_row['type'] == 'qqpay') ? ( // 如果是QQ支付
                ($qr_row['hook_type'] == '0') ? '云端挂机->' : 'PC挂机->' // 根据挂机类型设置挂机方式
            ) : ( // 如果是微信支付
                ($qr_row['hook_type'] == '0') ? '店员挂机->' : ( // 根据挂机类型设置挂机方式
                    ($qr_row['hook_type'] == '1') ? 'PC挂机->' : '云端挂机->'
                )
            )
        );
    
        // 根据支付类型设置具体挂机描述
        $zh .= ($qr_row['type'] == 'alipay') ? ( // 如果是支付宝支付
            ($qr_row['cookie'] == 'xfqymckxy') ? '支付宝签约免CK挂机' : ( // 如果是签约免CK
                ($qr_row['cookie'] == 'xfqydmfxy') ? '支付宝签约当面付挂机' : '支付宝云端协议挂机' // 如果是签约当面付
            )
        ) : (
            ($qr_row['type'] == 'qqpay') ? ( // 如果是QQ支付
                ($qr_row['xf_stat'] == '1') ? '云端不掉线通道' : '云端协议' // 根据支付通道设置描述
            ) : ( // 如果是微信支付
                ($qr_row['status'] == 1) ? '状态:在线' : '状态:掉线' // 根据状态设置描述
            )
        );
    
        return $zh; // 返回描述信息
    }
    private function userrow($pid){
        $sql = "SELECT * FROM pay_user WHERE  `pid` = :pid LIMIT 1";
        $paramsSelect = [
            'pid' => $pid
        ];
        
        return safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
    }
    private function userrow_user($user){
        $sql = "SELECT * FROM pay_user WHERE  `user` = :user LIMIT 1";
        $paramsSelect = [
            'user' => $user
        ];
        return safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
    }
    private function pctokenverify($token){
        $token1= aes256auth($token,PCTOKENKEY,"DECODE");
        
        if(!$token1)return false;
        $json = json_decode($token1,true);
        
        if(!$json)return false;
        $pid=$json['pid'];
        $key = $json['key'];
        
        $sql = "SELECT * FROM pay_user WHERE `pid`=:pid and `key`=:key limit 1";
        $paramsSelect = [
            'pid' => $pid,
            'key'=> $key
        ];
        $userrow = safeSqlQuery($sql, $paramsSelect)['result'][0];
        if($userrow){
            return array(
                   "pid"=>$pid,
                   "key"=>$key
               );
        }
        return false;
    }
}



?>